Bubble Sort

20
4 x

DESCRIPTION


Just like the way bubbles rise from the bottom of a glass, bubble sort is a simple algorithm that sorts a list, allowing either lower or higher values to bubble up to the top. The algorithm traverses a list and compares adjacent values, swapping them if they are not in the correct order.

It's a really simple and intuitive algorithm that does not require additional memory, but it's not really efficient on big data structures due to its quadratic time complexity.



COMPLEXITY


Average Case O(n 2)
Best Case O(n)
Worst Case O(n 2)
Space complexity    O(1)


IMPLEMENTATIONS



C++

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void BubbleSort(int arr[], int n)
{
    int i, j;
    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n-1-i; j++)
        {
            if (arr[j] > arr[j+1])
            {
                swap(&arr[j], &arr[j+1]);
            }
        }
    }
}

Javascript

function BubbleSort(array) 
{
    for (let i = 0; i < array.length-1; i++) 
    {
        for (let j = 0; j < array.length-1-i; j++) 
        {
            if (array[j] > array[j+1])
            {
                [array[j], array[j+1]] = [array[j+1], array[j]]; 
            }
        }                              
    }
}